//
//  UserAccountViewModel.m
//  weibo-OC
//
//  Created by diyuyma on 16/3/16.
//  Copyright © 2016年 zhangkaiyun. All rights reserved.
//

#import "UserAccountViewModel.h"
#import "AFNetworking.h"
#import "UserAccount.h"

@implementation UserAccountViewModel

//用户是否登录的属性

- (BOOL)userLogin {
    
    return self.account.access_token != nil;
}

- (NSString *)token {
    return self.account.access_token;
}

- (NSString *)userName {
    return self.account.name;
}

//用户头像 url
- (NSURL *)headURL {
    return [NSURL URLWithString:self.account.avatar_large];
}

//在init方法中获取 用户账户
- (instancetype)init {
    self.account = [[UserAccount alloc] init].loadAccount;
    return self;
}

- (void)loadAccessToken:(NSString *)code WithFinished:(void (^)(NSError *error))finished {
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    NSMutableDictionary * parameters = [NSMutableDictionary dictionaryWithCapacity:3];
    [parameters setObject:client_id forKey:@"client_id"];
    [parameters setObject:client_secret forKey:@"client_secret"];
    [parameters setObject:@"authorization_code" forKey:@"grant_type"];
    [parameters setObject:code forKey:@"code"];
    [parameters setObject:redirect_uri forKey:@"redirect_uri"];
    
    [[NetworkTools sharedTools] requestJsonDict:POST WithUrlString:urlString WithParameters:parameters WithFinished:^(NSDictionary *result, NSError *error) {
        
        if (error != nil) {
            finished(error);
            return ;
        }
        // 执行成功
        UserAccount *account = [[UserAccount alloc] initWithDict:result];
        [self loadUserInfoUserAccount:account WithFinished:^(NSError *error) {
        finished(nil);
        }];
    }];
}

//
- (void)loadUserInfoUserAccount: (UserAccount *)account WithFinished: (void(^)(NSError *error))finished{
    
    NSString *urlString = @"https://api.weibo.com/2/users/show.json";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:10];
    [parameters setObject:account.access_token forKey:@"access_token"];
    [parameters setObject:account.uid forKey:@"uid"];
    [[NetworkTools sharedTools] requestJsonDict:GET WithUrlString:urlString WithParameters:parameters WithFinished:^(NSDictionary *result, NSError *error) {
        if (error != nil) {
            finished(error);
            return ;
        }
        account.avatar_large = result[@"avatar_large"];
        account.name = result[@"name"];
        [account saveAccount];
        finished(error);
    }];
}




@end
